package com.study.boot.activiti.controller;

import com.tfd.base.utils.CryptoUtils;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

/**
 * 人员控制器
 *
 * @author TangFD@HF 2018/5/2
 */
@Controller
public class UserController {
    @Resource
    private IdentityService identityService;

    @GetMapping("role")
    public String role(Model model) {
        List<Group> groups = identityService.createGroupQuery().list();
        model.addAttribute("groups", groups);
        return "role";
    }

    @GetMapping("toAddRole")
    public String toAddRole(Model model, String groupId) {
        if (StringUtils.isEmpty(groupId)) {
            return "toAddRole";
        }

        Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
        model.addAttribute("group", group);
        return "toAddRole";
    }

    @PostMapping("addRole")
    public String addRole(@RequestParam String groupId, @RequestParam String groupName) {
        Group group = identityService.newGroup(groupId);
        group.setName(groupName);
        identityService.saveGroup(group);
        return "redirect:role";
    }

    @GetMapping("user")
    public String user(Model model) {
        List<User> users = identityService.createUserQuery().list();
        model.addAttribute("users", users);
        return "user";
    }

    @GetMapping("toAddUser")
    public String toAddUser(Model model, String userId) {
        List<Group> groups = identityService.createGroupQuery().list();
        model.addAttribute("groups", groups);
        if (StringUtils.isEmpty(userId)) {
            return "toAddUser";
        }

        User user = identityService.createUserQuery().userId(userId).singleResult();
        List<Group> groupList = identityService.createGroupQuery().groupMember(userId).list();
        model.addAttribute("user", user);
        model.addAttribute("group", groupList.get(0));
        return "toAddUser";
    }

    @PostMapping("addUser")
    public String addUser(@RequestParam String userId, @RequestParam String userName, String email, @RequestParam String password, @RequestParam String groupId) {
        User user = identityService.newUser(userId);
        user.setFirstName(userName);
        user.setEmail(email);
        user.setPassword(CryptoUtils.md5Encrypt(password));
        identityService.saveUser(user);
        identityService.createMembership(userId, groupId);
        return "redirect:user";
    }

}
